﻿using ConmonDateModel.ResponseBase;
using DateDBControl;
using DateDBControl.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using MyLogProject;
using MyProjectControlApplication.EncrypAndDecryp;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using ServiceControl;
using System.ComponentModel;
using System;
using System.Data.SqlTypes;
using System.Net;
using System.Reflection;
using System.Xml.Linq;
using System.ComponentModel.Design;
using ServiceControl.Helps;
using MyProjectControlApplication.Interfaces;
using Microsoft.AspNetCore.Authorization;
using MyProjectControlApplication.Authority.model;
using ConmonDateModel;

namespace MyProjectControlApplication.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.v1))]
    public class DeviceDateComtrol : ControllerBase
    {
        private readonly ICacheService _cacheService;
        /// 构造
        public DeviceDateComtrol( ICacheService cacheService)
        {
            _cacheService= cacheService;
        }

        /// <summary>
        /// 超管理员添加模块接口
        /// </summary>
        /// <param name="uuid">唯一标识</param>
        /// <param name="modulename">模块名</param>
        ///  <param name="version">版本号</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToCreatModule(string uuid,string modulename,string version)
        {
            ResponseBody rsult = AppDataServiceControl.ToAddTargetModule(uuid, modulename, version);
            return rsult;
        }


        /// <summary>
        /// 超管删除指定模块
        /// </summary>
        /// <param name="uuid">唯一</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToDeleteModuleItem(string uuid)
        {
            ResponseBody rsult = AppDataServiceControl.ToDeleteTargetModule(uuid);
            return rsult;
        }


        /// <summary>
        /// 获取所有模块
        /// </summary>
        ///  <param name="deviceid">设备ID</param>
        ///  <param name="modulename">模块名</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpGet]
        public ResponseBody GetAdllModule(string? deviceid,string? modulename)
        {
            ResponseBody reuslt = new ResponseBody();
            reuslt = AppDataServiceControl.ToGetAllModule(deviceid, modulename);
            return reuslt;
        }


        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="usermodel">用户信息(Json)</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToAddUser([FromBody]UserModel usermodel)
        {
            string _uuid = Guid.NewGuid().ToString("N");
            usermodel.uuid = _uuid;
            ResponseBody rsult = AppDataServiceControl.ToAddUser(usermodel);
            return rsult;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPost]
        public ResponseBody ToLogin(string username, string password)
        {
            ResponseBody reuslt = new ResponseBody();
            reuslt = AppDataServiceControl.ToGetTargetUser(username, password);
            if (reuslt.Code==ErrorCode.OK) 
            {
                var itemUser=JsonConvert.DeserializeObject<UserModel>(reuslt.Data.ToString());
                var products = _cacheService.GetData<string>(itemUser.token);
                if (products == null || !products.Any())
                {
                    //如果缓存中没有数据, 存入缓存
                    bool IsOk=_cacheService.SetData(itemUser.token, itemUser.token);
                    reuslt.Code = IsOk ? ErrorCode.OK : ErrorCode.Unknown;
                    reuslt.Description = IsOk ?"": "数据异常,请联系管理员";
                }
            }
            return reuslt;
        }


        /// <summary>
        /// 获取所有公司数量
        /// </summary>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public ResponseBody GetAllCompanyNum()
        {
            ResponseBody reuslt = new ResponseBody();
            reuslt = AppDataServiceControl.ToGetAllCompanyNum();
            return reuslt;
        }

        /// <summary>
        /// 添加公司
        /// </summary>
        /// <param name="companyname">公司名</param>
        /// <param name="linkman">联系人</param>
        /// <param name="linkPhone">联系电话</param>
        /// <param name="description">额外描述</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpPost]
        public ResponseBody ToAddCompany(string companyname, string? linkman, string? linkPhone , string? description)
        {
            string _uuid= Guid.NewGuid().ToString("N");
            var _codeuuid = Guid.NewGuid().ToString("N");
            Random random = new Random();
            int startIndex = random.Next(0, _codeuuid.Length - 5); // 确保至少有6位数字
            string randomSixDigits = _codeuuid.Substring(startIndex, 6);
            string _code = "Y" + randomSixDigits.ToUpper();
            var _Token=HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            ResponseBody rsult = AppDataServiceControl.ToAddTargetCompany(_code, _uuid, companyname, linkman, linkPhone, description, _Token);
            return rsult;
        }



        /// <summary>
        /// 更新目标公司信息
        /// </summary>
        /// <param name="uuid">公司唯一id</param>
        ///   <param name="code">公司编码</param>
        /// <param name="companyname">公司名</param>
        /// <param name="linkman">联系人</param>
        /// <param name="linkPhone">联系电话</param>
        /// <param name="description">额外描述</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpPost]
        public ResponseBody ToUpdatedCompany(string uuid, string code, string companyname, string? linkman, string? linkPhone, string? description)
        {
            var _Token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            ResponseBody rsult = AppDataServiceControl.ToUpdateTargetCompany(code, uuid, companyname, linkman, linkPhone, description, _Token);
            return rsult;
        }


        /// <summary>
        /// 删除公司(公司下所有设备)
        /// </summary>
        /// <param name="uuid">公司唯一标识</param>
        /// <param name="iscleardevice">是否清空公司下所有设备</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToDeleteCompany(string uuid,bool iscleardevice)
        {

            ResponseBody rsult = AppDataServiceControl.ToDeleteTargetCompany(uuid, iscleardevice);
            return rsult;
        }


        /// <summary>
        /// 获取所有设备数量
        /// </summary>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public ResponseBody GetAllDeviceNum()
        {
            ResponseBody reuslt = AppDataServiceControl.ToGetAllDeviceNum();
            return reuslt;
        }

        /// <summary>
        /// 分页获取公司信息列表
        /// </summary>
        /// <param name="companycode">公司编码</param>
        /// <param name="companyname">公司名</param>
        /// <param name="inputpagecode">当前页</param>
        /// <param name="inputpagesize">每页显示数量</param>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public ResponseBody GetCompanyByPage(string? companycode, string? companyname,int inputpagecode, int inputpagesize)
        {
            ResponseBody reuslt = AppDataServiceControl.ToGetCompanyByPage(companycode, companyname,inputpagecode, inputpagesize);
            return reuslt;
        }

        /// <summary>
        /// 模糊查询获取公司信息
        /// </summary>
        /// <param name="code">公司编码</param>
        /// <param name="companyname">公司名</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpGet]
        public ResponseBody GetCompanyBySearch(string? code, string? companyname)
        {
            ResponseBody reuslt = AppDataServiceControl.ToGetCompanyBySearch(code, companyname);
            return reuslt;
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="companyid">所属公司,公司唯一识别码</param>
        /// <param name="_devicename">设备名</param>
        /// <param name="robatmac">机器码</param>
        /// <param name="license">注册码</param>
        /// <param name="effecttime">授权截至日期</param>
        /// <param name="username">用户账号</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpPost]
        public ResponseBody ToAddDeviceByCompany(string companyid,string _devicename, string robatmac, string license, DateTime effecttime,string username)
        {
            string _uuid = Guid.NewGuid().ToString("N");
            ResponseBody reuslt = AppDataServiceControl.ToAddDeviceByCompany(_uuid, companyid, _devicename, robatmac, license, effecttime, username);
            return reuslt;
        }


        /// <summary>
        /// 更新设备信息
        /// </summary>
        /// <param name="uuid">设备唯一标识</param>
        /// <param name="devicename">设备名</param>
        /// <param name="license">注册码</param>
        /// <param name="effecttime">授权截至日期</param>
        /// <param name="username">用户账户</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpPost]
        public ResponseBody ToUpdateDevice(string uuid,string devicename, string license, DateTime effecttime,string username)
        {
            
            ResponseBody reuslt = AppDataServiceControl.ToUpdateDevice(uuid, devicename,license, effecttime, username);
            return reuslt;
        }


        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="uuid">设备唯一标识符</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToDeleteDevice(string uuid)
        {
            ResponseBody reuslt = AppDataServiceControl.ToDeleteTargetDevice(uuid);
            return reuslt;
        }


        ///// <summary>
        ///// 分页获取设备信息
        ///// </summary>
        ///// <param name="inputpagecode">当前页</param>
        ///// <param name="inputpagesize">每页显示数量</param>
        ///// <returns></returns>
        //[HttpGet]
        //public ResponseBody ToGetAllDeviceByPage(int inputpagecode, int inputpagesize)
        //{

        //    ResponseBody reuslt = AppDataServiceControl.ToGetAllDeviceByPage(inputpagecode, inputpagesize);
        //    return reuslt;
        //}



        /// <summary>
        /// 根据公司id分页获取公司所有设备
        /// </summary>
        ///  <param name="companycode">公司编码</param>
        ///   <param name="companyname">公司名</param>
        ///   <param name="robatmac">机器码</param>
        /// <param name="inputpagecode">当前页</param>
        /// <param name="inputpagesize">每页显示数量</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpGet]
        public ResponseBody ToGetDeviceByCompanyId(string? companycode, string? companyname,string? robatmac, int inputpagecode, int inputpagesize)
        {
            ResponseBody reuslt = AppDataServiceControl.ToGetDeviceBySearch(companycode, companyname, robatmac, inputpagecode, inputpagesize);
            return reuslt;
        }





        /// <summary>
        /// 单个为设备添加授权的模块
        /// </summary>
        /// <param name="devieid">设备ID</param>
        /// <param name="moduleid">模块ID</param>
        /// <param name="modulename">模块名</param>
        /// <param name="serverversion">模块版本</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost]
        public ResponseBody ToAddDeviceModule(string devieid, string moduleid, string modulename, string serverversion)
        {
            string _uuid = Guid.NewGuid().ToString("N");
            ResponseBody reuslt = AppDataServiceControl.ToAddDeviceModule(devieid, _uuid, moduleid, modulename, serverversion);
            return reuslt;
        }



        /// <summary>
        /// 设备信息维护
        /// </summary>
        /// <param name="devicedatejson">设备信息(Json)</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpPost]
        public ResponseBody ToAddOrUpdateDeviceInfo([FromBody]BatchAddDeviceModuleModel devicedatejson)
        {
            ResponseBody reuslt = new ResponseBody();

            try
            {
                var _Token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
                if (!string.IsNullOrEmpty(devicedatejson.deviceDate.license))
                {
                    string xmlKeys = EncrypAndDecrypControl.RSAPrivateKeyJavaToDotNet(EncrypAndDecrypControl.originalXmlKeys);
                    var _rsaStr = EncrypAndDecrypControl.RSADecrypt(xmlKeys, devicedatejson.deviceDate.license);
                    string[] arrayStr = _rsaStr.Split(',');
                    if (arrayStr.Length > 0)
                    {
                        string _TargetTimeStr = arrayStr[2];
                        DateTime tagetTime = Convert.ToDateTime(_TargetTimeStr);
                        bool IsDevceExits = AppDataServiceControl.IsDeviceExits(devicedatejson.deviceDate.uuid);
                        if (IsDevceExits)
                        {
                            reuslt = AppDataServiceControl.ToUpdateDevice(devicedatejson.deviceDate.uuid, devicedatejson.deviceDate.devicename, devicedatejson.deviceDate.license, tagetTime, _Token);
                            if (reuslt.Code == ErrorCode.OK)
                            {
                                reuslt = AppDataServiceControl.ToDeleteDeviceModule(devicedatejson.deviceDate.uuid);
                            }
                        }
                        else
                        {
                            string _uuid = Guid.NewGuid().ToString("N");
                            devicedatejson.deviceDate.uuid = _uuid;
                            reuslt = AppDataServiceControl.ToAddDeviceByCompany(_uuid, devicedatejson.deviceDate.companyid, devicedatejson.deviceDate.devicename, devicedatejson.deviceDate.robatmac, devicedatejson.deviceDate.license, tagetTime, _Token);
                        }
                        if (reuslt.Code == ErrorCode.OK)
                        {
                            if (devicedatejson.Items != null)
                            {
                                if (devicedatejson.Items.Count > 0)
                                {
                                    foreach (var item in devicedatejson.Items)
                                    {
                                        string _uuid = Guid.NewGuid().ToString("N");
                                        reuslt = AppDataServiceControl.ToAddDeviceModule(devicedatejson.deviceDate.uuid, _uuid, item.moduleid, item.modulename, item.serverversion);
                                    }
                                }
                            }
                        }

                    }
                }
                else
                {
                    reuslt.Code = ErrorCode.CommonError;
                    reuslt.Description = "注册码不能为空";
                }
            }
            catch (Exception ex) 
            {
                reuslt.Code = ErrorCode.CommonError;
                reuslt.Description ="格式解析出错";
            }


           
            return reuslt;
        }


        /// <summary>
        /// 更新设备模块信息
        /// </summary>
        /// <param name="itemsJson">客户端模块信息</param>
        /// <returns></returns>
    [TokenValidation]
        [HttpPost]
        public ResponseBody ToUpdateDeviceModule([FromBody] List<DeviceModeuleManagerModel> itemsJson)
        {
            ResponseBody reuslt = AppDataServiceControl.ToUpdateDeviceModule(itemsJson);
            return reuslt;
        }

        /// <summary>
        /// 删除对应设备下的模块
        /// </summary>
        /// <param name="uuid">模块uuid(唯一)</param>
        /// <returns></returns>
        //[HttpPost]
        //public ResponseBody ToDeleteDeviceModule(string uuid)
        //{
        //    ResponseBody reuslt = AppDataServiceControl.ToDeleteDeviceModule(uuid);
        //    return reuslt;
        //}


        /// <summary>
        ///  根据模块上传版本文件
        /// </summary>
        /// <param name="files">要上传的文件</param>
        /// <param name="moduleid">模块ID</param>
        /// <param name="modulename">模块名</param>
        /// <param name="version">版本号</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpPost("ToUploadFileAsync")]
        public async Task<ResponseBody> ToUploadFileAsync(IFormFile files,string moduleid,string modulename, string version)
        {
            var itemResult = new ResponseBody();
            try
            {
                var canNextResult = AppDataServiceControl.ToGetTargetModule(moduleid, version);
                if (canNextResult.Code!= ErrorCode.OK)
                {
                    return canNextResult;
                }

                string _fileName = files.FileName;
                string ItemFloder = $"Upload/{moduleid}/{version}/";
                string _FloderPath = AppDomain.CurrentDomain.BaseDirectory + ItemFloder;
                if (!Directory.Exists(_FloderPath))
                {
                    Directory.CreateDirectory(_FloderPath);
                }


                string _FilePath = ItemFloder + _fileName;

                string _CopyFilePath = _FloderPath + _fileName;
                if (files.Length > 0)
                {
                    using (var stream = new FileStream(_CopyFilePath, FileMode.Create))
                    {
                        await files.CopyToAsync(stream); //将文件流复制到指定位置
                    }
                }

                itemResult = AppDataServiceControl.ToUpdateModule(moduleid, _fileName, ItemFloder, version);
                if (itemResult.Code==ErrorCode.OK) 
                {
                    itemResult= AppDataServiceControl.ToAddHistoryModule(moduleid, modulename, _fileName, ItemFloder, version);
                }

            }
            catch (Exception ex)
            {
                itemResult.Code = ErrorCode.CommonError;
                itemResult.Data = ex.Message;
                LogManager.WriteLog(LogTypeEnum.Exception, "UploadFileAsync", ex.Message);
            }

            return itemResult;
        }


        /// <summary>
        /// 获取授权模块(客户端)
        /// </summary>
        /// <param name="robatmac">机器码</param>
        /// <returns></returns>
        [TokenValidation]
        [HttpGet]
        public ResponseBody ToGetAuthorizeModule(string robatmac)
        {
            ResponseBody _moduleResult = AppDataServiceControl.ToGetAuthorizeModuleByClient(robatmac);
         
            return _moduleResult;
        }

        /// <summary>
        /// 检查升级(客户端)
        /// </summary>
        /// <param name="robatmac">机器码</param>
        /// <returns></returns>       
        [TokenValidation]
        [HttpGet]
        public ResponseBody ToGetNeedDownModule(string robatmac)
        {
            ResponseBody _moduleResult = AppDataServiceControl.ToGetTargetModuleByClient(robatmac);
            if (_moduleResult.Code == ErrorCode.OK)
            {
                var  _Result = AppDataServiceControl.ToAddOperationLog(robatmac, "ToGetNeedDownModule");
                if (_Result.Code!=ErrorCode.OK) 
                {
                    _moduleResult.Description= _Result.Description;
                }
            }
            return _moduleResult;
        }


        /// <summary>
        /// 获取当前设备下所有模块
        /// </summary>
        /// <param name="robatmac"></param>
        /// <returns></returns>
     [TokenValidation]
        [HttpGet]
        public ResponseBody ToGeCurrentDeviceModule(string robatmac)
        {
            ResponseBody _moduleResult = AppDataServiceControl.ToGetTargetModuleByUpdate(robatmac);
           
            return _moduleResult;
        }
        /// <summary>
        /// 分页获取模块版本历史记录
        /// </summary>
        /// <param name="moduleid">模块ID</param>
        /// <param name="inputpagecode">当前页</param>
        /// <param name="inputpagesize">每页数量</param>
        /// <returns></returns>
 [TokenValidation]
        [HttpGet]
        public ResponseBody ToGetHistoryModuleByPage(string moduleid, int inputpagecode, int inputpagesize)
        {
            ResponseBody _moduleResult = AppDataServiceControl.ToGetHistoryModuleByPage(moduleid, inputpagecode, inputpagesize);
            return _moduleResult;
        }


        /// <summary>
        /// 根据模块下载最新版本文件
        /// </summary>
        /// <returns></returns>
 [TokenValidation]
        [HttpGet]
        public IActionResult ToDownloadTemplate(string filepath, string filename,string robatMac)
        {
            try
            {
                FileStreamResult result = null;

                //文件的服务器地址
                string filePath = AppDomain.CurrentDomain.BaseDirectory + filepath + $"//{filename}";
                //确定模板文件是否存在
                if (!System.IO.File.Exists(filePath))
                {
                    return BadRequest("服务端模板文件不存在！");
                }
                //返回流
                FileInfo fileMetaInfo = new System.IO.FileInfo(filePath);
                string _filesuffix = fileMetaInfo.Extension;
                // 创建文件读取流
                FileStream fileStream = System.IO.File.OpenRead(filePath);
                // 根据文件后缀获取文件的ContentType
                var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
                // 返回文件contentType类型
                var contentType = fileExtensionContentTypeProvider.Mappings[_filesuffix];
                result = File(fileStream, contentType, fileMetaInfo.Name);

                AppDataServiceControl.ToAddOperationLog(robatMac, "ToDownloadTemplate");

                return result;
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }


        /// <summary>
        /// 下载历史模块版本
        /// </summary>
        /// <param name="filepath">文件相对路径</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public IActionResult ToDownloadHistoryFile(string filepath, string filename)
        {
            try
            {
                FileStreamResult result = null;

                //文件的服务器地址
                string filePath = AppDomain.CurrentDomain.BaseDirectory + filepath + $"//{filename}";
                //确定模板文件是否存在
                if (!System.IO.File.Exists(filePath))
                {
                    return BadRequest("服务端模板文件不存在！");
                }



                //返回流
                FileInfo fileMetaInfo = new System.IO.FileInfo(filePath);
                string _filesuffix = fileMetaInfo.Extension;
                // 创建文件读取流
                FileStream fileStream = System.IO.File.OpenRead(filePath);
                // 根据文件后缀获取文件的ContentType
                var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
                // 返回文件contentType类型
                var contentType = fileExtensionContentTypeProvider.Mappings[_filesuffix];
                result = File(fileStream, contentType, fileMetaInfo.Name);

                return result;
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }


        /// <summary>
        /// 获取授权码
        /// </summary>
        /// <param name="macinfo">机器码</param>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public ResponseBody GetAuthorizationCode(string macinfo) 
        {
            var rsult = AppDataServiceControl.GetTargetAuthorizationCode(macinfo);
            if (rsult.Code==ErrorCode.OK) 
            {
                var  _rsult=AppDataServiceControl.ToAddOperationLog(macinfo, "GetAuthorizationCode");
                if (_rsult.Code!=ErrorCode.OK) 
                {
                    rsult.Description = _rsult.Description;
                }
            }
            return rsult;
        }


        /// <summary>
        /// 获取所有日志
        /// </summary>
        /// <param name="inputpagecode">页码</param>
        /// <param name="inputpagesize">每页数量</param>
        /// <returns></returns>
  [TokenValidation]
        [HttpGet]
        public ResponseBody GetLogDateByPage(int inputpagecode, int inputpagesize)
        {
            var rsult = AppDataServiceControl.GetAllLogByPage(inputpagecode, inputpagesize);        
            return rsult;
        }




    }
}
